package com.linq.cool.beauty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linq.cool.beauty.domain.BeautyProduct;
import com.linq.cool.beauty.domain.BeautyProductHistory;
import com.linq.cool.beauty.domain.BeautyProductStatistical;
import com.linq.cool.beauty.repository.BeautyProductHistoryRepository;
import com.linq.cool.beauty.service.BeautyProductHistoryService;
import com.linq.cool.beauty.service.BeautyProductService;
import com.linq.cool.beauty.service.BeautyProductStatisticalService;
import com.linq.cool.common.core.utils.IdWorker;
import com.linq.cool.common.core.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: yqlin
 * @Date: 2021/2/9 01:51
 * @Description:
 * @Version: 1.0.0
 */
@Slf4j
@Service
public class BeautyProductHistoryServiceImpl implements BeautyProductHistoryService {
    @Autowired
    private BeautyProductHistoryRepository beautyProductHistoryRespository;
    @Autowired
    private BeautyProductStatisticalService beautyProductStatisticalService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BeautyProductService beautyProductService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 这里不采用事务 相应处理应该互不影响
     *
     * @param productHistory
     */
    @Override
    public void save(BeautyProductHistory productHistory) {
        try {
            productHistory.setId(idWorker.nextId());
            BeautyProduct product = beautyProductService.getById(productHistory.getProductId());
            productHistory
                    .setProductPrice(product.getPrice())
                    .setProductBrandId(product.getBrandId())
                    .setProductBrandName(product.getBrandName())
                    .setProductCategoryId(product.getProductCategoryId())
                    .setProductName(product.getName())
                    .setProductPic(product.getPic())
                    .setMemberId(SecurityUtils.getUserId())
                    .setCreateTime(new Date().toString());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            productHistory.setCreateDay(sdf.format(new Date()));
            // 保存
            beautyProductHistoryRespository.save(productHistory);
            BeautyProductStatistical productStatistical = beautyProductStatisticalService.getOne(new LambdaQueryWrapper<BeautyProductStatistical>()
                                                                                                         .eq(BeautyProductStatistical::getProductId, productHistory.getProductId())
            );
            if (null == productStatistical) {
                beautyProductStatisticalService.save(new BeautyProductStatistical().setProductId(productHistory.getProductId()).setHistoryCount(1));
            } else {
                // 浏览数+1
                productStatistical.setHistoryCount(productStatistical.getHistoryCount() + 1);
                beautyProductStatisticalService.updateById(productStatistical);
            }
        } catch (Exception e) {
            log.error("保存历史记录异常：", e);
        }
    }

    @Override
    public void clearHistory() {
        Query query = new Query();
        query.addCriteria(Criteria.where("member_id").is(SecurityUtils.getUserId()));
        mongoTemplate.remove(query, BeautyProductHistory.class);
    }

    @Override
    public Map<String, List<BeautyProductHistory>> listByPage(long current, long size) {
        // 构造查询对象
        Query query = new Query();
        // 设置参数
        query.addCriteria(Criteria.where("member_id").is(SecurityUtils.getUserId()));
        // 设置跳过多少条
        query.skip((current - 1) * size);
        // 取出多少条
        query.limit(Math.toIntExact(size));
        // 构造排序对象
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "create_time");
        // 设置排序对象
        query.with(Sort.by(order));
        // 查询
        List<BeautyProductHistory> list = mongoTemplate.find(query, BeautyProductHistory.class);
        return list.stream().collect(Collectors.groupingBy(BeautyProductHistory::getCreateDay));
    }

    @Override
    public void removeById(Long productHistoryId) {
        // 先查询再删除
        BeautyProductHistory one = beautyProductHistoryRespository.findByIdAndMemberId(productHistoryId, SecurityUtils.getUserId());
        if (null != one) {
            beautyProductHistoryRespository.deleteById(productHistoryId);
        }
    }
}
